import { CircularProgress, Typography } from '@mui/material';
import { Box } from '@mui/system';
import { eachDayOfInterval, format, subDays } from 'date-fns';
import { enUS } from 'date-fns/locale';
import React, { useEffect, useState } from 'react';
import {
    Area,
    AreaChart,
    CartesianGrid,
    ResponsiveContainer,
    Tooltip,
    XAxis,
    YAxis
} from 'recharts';

import DisbursementManager from '../../api/disbursement/disbursement-manager';

const enum CHART_FILTER_TYPE {
    DAY,
    WEEK,
    MONTH,
    YEAR
}

// const filterChartOptions = [
//     {
//         value: CHART_FILTER_TYPE.DAY,
//         label: 'Day',
//     },
//     {
//         value: CHART_FILTER_TYPE.WEEK,
//         label: 'Week',
//     },
//     {
//         value: CHART_FILTER_TYPE.MONTH,
//         label: 'Month',
//     },
//     {
//         value: CHART_FILTER_TYPE.YEAR,
//         label: 'Year',
//     },
// ];

interface DisbursementChartData {
    id: number;
    amount: number;
    time: number;
}

const months = Array.from(Array(12).keys()).map((i) =>
    enUS.localize.month(i, { width: 'abbreviated' })
);

const CustomTooltip = (props) => {
    const { active, payload } = props;
    const currData = payload && payload.length ? payload[0].payload : null;
    if (active && currData) {
        const { timeKey, valueKey } = currData;
        return (
            <Box
                sx={{
                    background: '#1F1D37',
                    boxShadow: '0px 4px 6px rgba(19, 17, 42, 0.5)',
                    borderRadius: '6px',
                    padding: '12px',
                    position: 'relative',
                    boxSizing: 'border-box',
                    alignItems: 'center'
                }}
            >
                <Box display={'flex'} gap={1} alignItems={'center'}>
                    <Typography variant={'h6'}> {timeKey}</Typography>
                    <Typography variant={'body1'} fontWeight={500}>
                        {valueKey}
                    </Typography>
                </Box>
                <Box
                    sx={{
                        width: '0',
                        height: '0',
                        borderLeft: '10px solid transparent',
                        borderRight: '10px solid transparent',
                        borderTop: '10px solid #1F1D37',
                        position: 'absolute',
                        bottom: '-10px',
                        left: '50%',
                        transform: 'translateX(-50%)'
                    }}
                />
            </Box>
        );
    }

    return null;
};

export const EarningReportChart = () => {
    const [filterType] = useState<CHART_FILTER_TYPE>(CHART_FILTER_TYPE.DAY);
    const [disbursement, setDisbursement] = useState<DisbursementChartData[]>(undefined);
    const [chartData, setChartData] = useState([]);
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        setLoading(true);
        DisbursementManager.getAllPage()
            .then((listData) => {
                const disbursementChartData = listData
                    .map(({ id, timestamp, total_amount_in_usd }) => {
                        if (
                            total_amount_in_usd &&
                            new Date(timestamp).getFullYear() === new Date().getFullYear()
                        ) {
                            return {
                                id,
                                time: timestamp,
                                amount: total_amount_in_usd
                            };
                        } else {
                            return undefined;
                        }
                    })
                    .filter((data) => data);
                setDisbursement(disbursementChartData);
            })
            .finally(() => {
                setLoading(false);
            });
    }, []);

    useEffect(() => {
        if (disbursement && filterType !== undefined) {
            if (filterType === CHART_FILTER_TYPE.MONTH) {
                const finalData = months.reduce(
                    (prev, curr) => ({
                        ...prev,
                        [curr]: 0
                    }),
                    {}
                );
                disbursement.forEach(({ time, amount }) => {
                    const month = new Date(time).toLocaleString('default', { month: 'long' });
                    finalData[month] = finalData[month] + amount;
                });
                const chartData = months.map((month) => ({
                    timeKey: month,
                    valueKey: finalData[month]
                }));
                setChartData(chartData);
            } else if (filterType === CHART_FILTER_TYPE.DAY) {
                const now = new Date();
                const recentDays = eachDayOfInterval({
                    start: subDays(now, 14),
                    end: now
                }).map((day) => format(day, 'MM-dd'));
                const finalData = recentDays.reduce(
                    (prev, curr) => ({
                        ...prev,
                        [curr]: 0
                    }),
                    {}
                );
                disbursement.forEach(({ time, amount }) => {
                    const day = format(time, 'MM-dd');
                    finalData[day] = finalData[day] + amount;
                });
                const chartData = recentDays.map((day) => ({
                    timeKey: day,
                    valueKey: finalData[day]
                }));
                setChartData(chartData);
            }
        }
    }, [disbursement, filterType]);

    return (
        <Box
            sx={{
                background: '#0B0821',
                borderRadius: '12px',
                p: 3,
                mt: 4,
                '& .recharts-wrapper': {
                    marginLeft: 'auto',
                    marginRight: 'auto'
                }
            }}
        >
            <Box display={'flex'} justifyContent={'space-between'} py={3}>
                <Typography variant={'h4'}>Earnings Report</Typography>
                {/* <Box display={'flex'} sx={{ background: '#13112A', borderRadius: '5px' }}>*/}
                {/*    {filterChartOptions.map(({ label, value }) => (*/}
                {/*        <Typography*/}
                {/*            key={value}*/}
                {/*            variant={'subtitle2'}*/}
                {/*            className={filterType === value ? 'active' : ''}*/}
                {/*            sx={{*/}
                {/*                padding: 1,*/}
                {/*                fontSize: 12,*/}
                {/*                boxShadow: '0px 1.02542px 2.05084px rgba(0, 0, 0, 0.075)',*/}
                {/*                borderRadius: '5px',*/}
                {/*                cursor: 'pointer',*/}
                {/*                '&.active': {*/}
                {/*                    background: '#211F3D',*/}
                {/*                },*/}
                {/*            }}*/}
                {/*            onClick={() => setFilterType(value)}*/}
                {/*        >*/}
                {/*            {label}*/}
                {/*        </Typography>*/}
                {/*    ))}*/}
                {/* </Box>*/}
            </Box>
            <ResponsiveContainer minHeight={250}>
                {!loading ? (
                    <AreaChart data={chartData} margin={{ top: 10, right: 30, left: 0, bottom: 0 }}>
                        <defs>
                            <linearGradient id="colorUv" x1="0" y1="0" x2="0" y2="1">
                                <stop offset="5%" stopColor="#00C7FF" stopOpacity={0.7} />
                                <stop offset="95%" stopColor="#00C7FF" stopOpacity={0} />
                            </linearGradient>
                            <linearGradient id="colorPv" x1="0" y1="0" x2="0" y2="1">
                                <stop offset="5%" stopColor="#FF00A9" stopOpacity={0.4} />
                                <stop offset="95%" stopColor="#FF00A9" stopOpacity={0} />
                            </linearGradient>
                        </defs>
                        <XAxis tickLine={false} dataKey="timeKey" fontSize={11} />
                        <YAxis tickLine={false} fontSize={11} />
                        <CartesianGrid
                            stroke="#211F3D"
                            strokeWidth="0.5"
                            horizontal={true}
                            vertical={false}
                        />
                        <Tooltip content={<CustomTooltip />} />
                        <Area
                            type="monotone"
                            dataKey="valueKey"
                            stroke="#00C7FF"
                            fillOpacity={1}
                            fill="url(#colorUv)"
                        />
                        <Area
                            type="monotone"
                            dataKey="pv"
                            stroke="#FF00A9"
                            fillOpacity={1}
                            fill="url(#colorPv)"
                        />
                    </AreaChart>
                ) : (
                    <Box
                        display={'flex'}
                        justifyContent={'center'}
                        alignItems={'center'}
                        width={'100%'}
                        height={'100%'}
                    >
                        <CircularProgress />
                    </Box>
                )}
            </ResponsiveContainer>
        </Box>
    );
};
